package com.liang.maogouyuyin

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.os.Handler
import android.view.KeyEvent
import android.widget.FrameLayout
import androidx.core.view.children
import androidx.core.view.get
import androidx.fragment.app.Fragment
import androidx.viewpager.widget.ViewPager
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.core.BasePopupView
import com.liang.publics.ad.ads.AsService
import com.liang.publics.config.Const
import com.liang.publics.config.Logger
import com.liang.publics.ui.RTExitDialogPopup
import com.liang.publics.ui.SettingFragment
import com.liang.publics.util.LogUtil
import com.liang.publics.util.SharedPreferencesUtil
import com.liang.maogouyuyin.adapter.lzy.FragmentMainAdapter
import com.liang.maogouyuyin.base.lzy.LZYBaseActivity
import com.liang.maogouyuyin.databinding.ActivityMainBinding
import com.liang.maogouyuyin.ui.fragment.InteractFragment
import com.liang.maogouyuyin.ui.fragment.RecordFragment
import com.liang.maogouyuyin.ui.fragment.HomeFragment
import com.liang.maogouyuyin.ui.fragment.PetMenuFragment
import com.liang.maogouyuyin.utils.PlayerUtil
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

class MainActivity : LZYBaseActivity<ActivityMainBinding>(){

    private lateinit var binding: ActivityMainBinding

    private var fragments: MutableList<Fragment?> = mutableListOf()
    private lateinit var recordFragment: RecordFragment
    private lateinit var interactFragment: InteractFragment
    private lateinit var homeFragment: HomeFragment
    private lateinit var petMenuFragment: PetMenuFragment
    private lateinit var settingFragment: SettingFragment

    private lateinit var contexts:Context
    private lateinit var activitys: Activity

    companion object {

        fun forward(context: Context) {
            context.startActivity(Intent(context, MainActivity::class.java))
        }

        @JvmStatic
        fun gotoActivity(context: Context) {
            Logger.i(Const.TAG, "MainActivity--------gotoActivity")
            TheBaseApplication.ifMainActivity = true
            SplashActivity.ifSplashActivity = false

            val intent = Intent(context, MainActivity::class.java)
            context.startActivity(intent)
        }
    }

    override fun onPause() {
        PlayerUtil.stopAudio()
        super.onPause()
    }

    override fun createBinding(): ActivityMainBinding {
        binding= ActivityMainBinding.inflate(layoutInflater)
        return binding
    }

    override fun initViews() {
        setImmersionMode(true) //设置false关闭沉浸，设置true启动沉浸。如果部分fragment需要沉浸，部分不需要沉浸，请打开沉浸模式。使用baseFragment可选关闭沉浸,或者自己处理沉浸栏。
        contexts=this
        activitys=this

        initView()
        initSetting()

        EventBus.getDefault().register(this)
        adLoad(-1,this,this)
    }
    //developer---------------------------------------------------start
//    override fun provideToolbar(): Toolbar {
//        return binding.toolbar
//    }
    //developer---------------------------------------------------end

    private fun initView(){
    //developer---------------------------------------------------start
//        binding.toolbar.addToolBarBack()
//        binding.toolbar.addToolBarTitle("你好")
    //developer---------------------------------------------------end
/*        XPopup.Builder(this)
            .asCustom(MainPopup(this))
            .show()*/
    }

    private fun initSetting(){
        initViewpagerSetting()
        initBottomNavigationSetting()
    }

    private fun initViewpagerSetting(){
        //TODO:developer---------------------------------------------------start
        homeFragment = HomeFragment()
        interactFragment = InteractFragment()
        recordFragment = RecordFragment()
        petMenuFragment = PetMenuFragment()
        settingFragment = SettingFragment()
        fragments.add(homeFragment)
        fragments.add(interactFragment)
        fragments.add(recordFragment)
        fragments.add(petMenuFragment)
        fragments.add(settingFragment)
        //TODO:developer---------------------------------------------------end
        binding.viewPager.adapter = FragmentMainAdapter(supportFragmentManager, fragments)
        binding.viewPager.currentItem = 0
        binding.viewPager.offscreenPageLimit = binding.bottomNav.menu.size()
        binding.viewPager.setOnPageChangeListener(object : ViewPager.OnPageChangeListener {
            override fun onPageScrolled(
                position: Int,
                positionOffset: Float,
                positionOffsetPixels: Int
            ) {
                PlayerUtil.stopAudio()
            }

            override fun onPageSelected(position: Int) {
                binding.bottomNav.selectedItemId = binding.bottomNav.menu[position].itemId
                //adv---------------------------------------------------start
                /*if (position%2==0){
                    Log.i("lzy","page插屏1")
                }else{
                    Log.i("lzy","page插屏2")
                }*/
                adLoad(position, contexts, activitys)
                //adv---------------------------------------------------end
                PlayerUtil.stopAudio()
            }

            override fun onPageScrollStateChanged(state: Int) {}
        })
    }

    private fun initBottomNavigationSetting(){
        binding.bottomNav.itemIconTintList = null
        // 监听底部导航栏的选中事件，并设置ViewPager页面随之切换
        binding.bottomNav.setOnNavigationItemSelectedListener { item ->
            // 获取菜单项在菜单中的索引
            val index = binding.bottomNav.menu.children.indexOf(item)
            // 设置 ViewPager 当前页面为对应索引
            if (index >= 0) {
                binding.viewPager.setCurrentItem(index, true) // 第二个参数表示是否平滑滚动
                return@setOnNavigationItemSelectedListener true
            }
            false
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        EventBus.getDefault().unregister(this)
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<String?>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onMessageEvent(type: String) {

    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean {
        // 监听返回键，点击两次退出程序
        if (SharedPreferencesUtil.getStatus(SharedPreferencesUtil.IF_AD)  && keyCode == KeyEvent.KEYCODE_BACK && event.action == KeyEvent.ACTION_DOWN) {
            showExitDialog()
            return true
        }
        return super.onKeyDown(keyCode, event)
    }

    private var exitPopupView: BasePopupView? = null
    var isExitApp = false

    private fun showExitDialog() {
        val customPopup = RTExitDialogPopup(this)
        customPopup.listener = object : RTExitDialogPopup.OnExitClickListener {
            override fun cancel() {
                isExitApp = true
            }

            override fun closeDialog() {
                isExitApp = false
            }

            override fun ok() {
                isExitApp = false
            }

        }
        exitPopupView = XPopup.Builder(this)
            .autoOpenSoftInput(false)
            .autoDismiss(false)
            .dismissOnBackPressed(false)
            .dismissOnTouchOutside(false)
            .asCustom(customPopup)
            .show()
    }

    fun adLoad( position:Int ,context: Context ,activity: Activity){
        val ad2 = SharedPreferencesUtil.getStatus(SharedPreferencesUtil.IF_AD_2) //自然流量广告模式

        LogUtil.i(Const.TAG,"MainActivity---------------adLoad----------------$position")
        if (SharedPreferencesUtil.getStatus(SharedPreferencesUtil.IF_AD) || (position == 0 && ad2) ) {


            val adService = AsService()
            var mFeedContainer: FrameLayout? = null
            var mFeedContainer2: FrameLayout? = null

            var feedId = resources.getString(R.string.feed_native_media_id)
            var feedId2 = resources.getString(R.string.feed_native_media_2_id)
            when (position) {
                0 -> {
                    mFeedContainer = HomeFragment.mFeedContainer;
                    //mFeedContainer2 = weatherFragment.fl_content_0;
                }
                1 -> {
                    mFeedContainer = InteractFragment.mFeedContainer;
                    //mFeedContainer2 = calendarFragment.fl_content_11;
                }
                2 -> {
                    mFeedContainer = RecordFragment.mFeedContainer;
                    //mFeedContainer2 = fortuneFragment.fl_content_22;
                }
                3 -> {
                    feedId = feedId2
                    mFeedContainer = SettingFragment.mFeedContainer;
                }
            }
            adService.initAd(
                "feed",
                context,
                feedId,
                mFeedContainer
            )
            adService.showAd("feed", activity)

            //插屏
            adService.initAd("full", context, resources.getString(R.string.full_media_id), null)

            //显示插屏
            Handler().postDelayed({ adService.showAd("full", activity) }, 1500)

            if (!ad2) {
                adService.initAd(
                    "full2", context, resources.getString(R.string.full_media_2_id),
                    null
                )

                Handler().postDelayed({adService.showAd("full2", activity) }, 1500)
                SharedPreferencesUtil.saveStatus("first_launch_list_fragment", true)
            }
        }
    }
}